package com.example.home_app.base.activity

import android.graphics.Color
import android.os.Bundle
import android.os.Handler
import android.os.Looper
import android.view.View
import android.view.ViewGroup


import com.android.frame.mvp.CommonBaseActivity
import com.android.widget.PopupWindow.CommonPopupWindow

import com.example.home_app.R
import com.example.home_app.databinding.ActicityDeviceLedBinding
import com.example.home_app.http.base.onenetdevice.Data
import com.example.home_app.http.base.onenetdevice.GetRootBean
import com.example.home_app.util.Json
import com.example.home_app.util.State
import com.example.home_app.util.Utils

import com.gyf.immersionbar.ImmersionBar
import okhttp3.*
import java.io.BufferedReader
import java.io.IOException
import java.io.InputStreamReader
import java.net.HttpURLConnection
import java.net.URL
import java.util.*

/**
 * Created by dell on 2021/8/11.
 */
class LedActivity: CommonBaseActivity<ActicityDeviceLedBinding>() {
    private var okHttpClient: OkHttpClient? = null
    private var mPopupWindow: CommonPopupWindow? = null
    private var online: String? = null
    private var responseData: String? = null
    private var ID: String? = null
    private var name: String? = null
    private var ONOFF: String? = null

    private var create_time: Date? = null
    private var create_t: String? = null
    private var unit_symbol: String? = null
    private var update_at: Date? = null
    private var update_t: String? = null
    private val uuid: String? = null
    private var current_value = 0



    var send = true
    companion object {
        const val EXTRA_ID = "EXTRA_ID"
        const val EXTRA_MAME = "EXTRA_MAME"
        const val EXTRA_ONLINE = "EXTRA_ONLINE"
    }
    override fun handleView(savedInstanceState: Bundle?) {
        intView()
        initData()
    }
    private fun intView(){

        ImmersionBar.with(this).titleBar(binding.toolbar).init()
        ImmersionBar.with(this).titleBar(binding.toolbar).keyboardEnable(true).init()
        setSupportActionBar(binding.toolbar)
        val actionBar = supportActionBar
        actionBar?.setDisplayHomeAsUpEnabled(true)
    }
    override fun initListener() {
        //toolbar返回按钮监听
        binding.ivAdd.setOnClickListener {
            showToBottomWindow1(View(this))
        }
        //toolbar返回按钮监听
        binding.toolbar.setNavigationOnClickListener { finish() }
        //修改状态
        binding.switchLed.setOnClickListener {
            ONOFF = if (current_value == 1) {
                "0"
            } else {
                "1"
            }
            send = true
            postInformation(ONOFF !!)
            }

    }

    private fun initData() {
        okHttpClient = OkHttpClient()
        val bundle = intent.extras
        if (bundle != null) {
            ID = bundle.getString(EXTRA_ID)
            online = bundle.getString(EXTRA_ONLINE)
            binding.toolbar.title = bundle.getString(EXTRA_MAME)
        }
        println(ID)
        binding.saiId.text = ID
        binding.online.text = online
        if (online === "√") {
            //String o = String.valueOf(devices.get(i).getOnline());
            binding.online.setTextColor(Color.GREEN)
        } else {
            binding.online.setTextColor(Color.RED)
        }
        State.OTHER = false
        getInformation()

    }

    private fun getInformation() {
        okHttpClient = OkHttpClient()
        val request = Request.Builder()
            .url("http://api.heclouds.com/devices/$ID/datastreams/")
            .header("api-key", State.ApiKey).build()
        val call = okHttpClient !!.newCall(request)
        call.enqueue(object : Callback {
            @Throws(IOException::class)
            override fun onResponse(call: Call, response: Response) {
                try {
                    responseData = response.body() !!.string()
                    val app: GetRootBean = Json.gson !!.fromJson(
                        responseData,
                        GetRootBean::class.java
                    )
                    val streams = app.getData() as List<Data>
                    update_at = streams[0].getUpdate_at()
                    create_time = streams[0].getCreate_time()
                    current_value = streams[0].getCurrent_value() !!.toInt()
                    unit_symbol = streams[0].getUnit_symbol()
                    println(streams[0].getId())
                    name = streams[0].getId()
                    update_t = Utils.dateToString(update_at, "yyyy-MM-dd HH:mm:ss")
                    create_t = Utils.dateToString(create_time, "yyyy-MM-dd HH:mm:ss")
                    Handler(Looper.getMainLooper()).postDelayed({
                        if (State.DeviceIDs != ""){
                            binding.updatetime.text = update_t
                            binding.createTime.text = create_t
                            if (current_value == 0) {
                                binding.zhuangtai.text = "设备已打开"
                                binding.switchLed.setImageResource(R.mipmap.sss)
                            } else {
                                binding.zhuangtai.text = "设备已关闭"
                                binding.switchLed.setImageResource(R.mipmap.sss1)
                            }
                        }
                    }, 200)

                } catch (e: IOException) {
                    e.printStackTrace()
                }
            }

            override fun onFailure(call: Call, e: IOException) {}
        })
    }

    private fun postInformation(onoff: String) {
        // Android 4.0 之后不能在主线程中请求HTTP请求
        Thread {
            val url: URL
            val connection: HttpURLConnection
            try {
                println(onoff)
                //data1代表云端的数据流是data1
                val s1: String = (",;$name,$onoff")
                val data = s1.toByteArray()
                // 先new出一个URL对象，传入网络地址
                // 调用openConnection()方法获取到HttpURLConnection对象
                // 自己创建的中移物联网的地址http://api.heclouds.com/devices/25857699/datapoints?type=5
                url = URL(
                    "http://api.heclouds.com/devices/" + ID
                            + "/datapoints?type=5"
                )
                connection = url.openConnection() as HttpURLConnection
                // 下面使一些自由的定制，比如设置连接超时，读取超时的毫秒数，以及服务器希望得到的一些消息头
                connection.connectTimeout = 8000
                connection.readTimeout = 8000
                connection.doOutput = true
                connection.doInput = true
                connection.requestMethod = "POST"
                connection.setRequestProperty("api-key",State.ApiKey)
                connection.setRequestProperty("Content-Length", data.size.toString())
                connection.setChunkedStreamingMode(5)
                // 设置打开输出流
                connection.doOutput = true
                // 拿到输出流
                val os = connection.outputStream
                // 使用输出流往服务器提交数据
                os.write(data)
                os.flush()
                os.close()
                // //如果请求发送成功
                if (connection.responseCode == 200) {

                    // 接下来利用输入流对数据进行读取
                    val `is` = connection.inputStream
                    val br = BufferedReader(
                        InputStreamReader(`is`)
                    )
                    val response = StringBuilder()
                    var line: String?
                    while ((br.readLine().also { line = it }) != null) {
                        response.append(line)
                    } // 正常则返回{"errno":0,"error":"succ"}，此函数为void，用不上这个
                }
                // 最后关闭HTTP连接
                connection.disconnect()

            } catch (e: Exception) {
                e.printStackTrace()
            }
            Handler(Looper.getMainLooper()).postDelayed({
                /*获取跟新数据*/
                getInformation()
            }, 300)
        }.start()


    }

    //向下弹出
    private fun showToBottomWindow1(view: View) {
        if (mPopupWindow != null && mPopupWindow!!.isShowing)
            return
        mPopupWindow = CommonPopupWindow.Builder(this)
            .setContentView(R.layout.layout_pop_add)
            .setViewParams(
                ViewGroup.LayoutParams.MATCH_PARENT,
                ViewGroup.LayoutParams.WRAP_CONTENT
            )

            .setOutsideTouchable(true)
            .setAnimationStyle(R.style.TopAnimation)
            .setBackGroundAlpha(0.8f)
            .setOnViewListener { holder, popupWindow ->
                holder.setOnClickListener(R.id.tv_1) { showToast("已在当前页面"); popupWindow.dismiss()}
                holder.setOnClickListener(R.id.tv_2) {
                    val bundle = Bundle()
                    bundle.putString(HistoryDataActivity.EXTRA_ID, ID)
                    startActivity(HistoryDataActivity::class.java , bundle)
                    popupWindow.dismiss()}
                holder.setOnClickListener(R.id.tv_3) { showToast("3"); popupWindow.dismiss() }
                holder.setOnClickListener(R.id.tv_4) { showToast("4"); popupWindow.dismiss() }
                holder.setOnClickListener(R.id.tv_5) { showToast("5"); popupWindow.dismiss()}

            }
            .build()
        mPopupWindow!!.showAsDropDown(binding.ivAdd,-100,0)

    }


}
